from common.pagenation import Paging
from daos import get_db_session, get_update_contents
from models.system_user import SystemUser


def add_system_user(user_orm: SystemUser, is_commit=True):
    # now = datetime.now()
    session = get_db_session()

    session.add(user_orm)
    session.commit() if is_commit else session.flush()
    return user_orm


def update_system_user(user_orm: SystemUser, *args, is_commit=True):
    session = get_db_session()
    update_contents = get_update_contents(user_orm, *args)
    session.query(SystemUser).filter(SystemUser.id == user_orm.id).update(update_contents)
    session.commit() if is_commit else session.flush()
    return


def query_system_user(pk):
    return get_db_session().query(SystemUser).filter(SystemUser.id == pk).first()


def query_system_user_by_username(username):
    return get_db_session().query(SystemUser).filter(SystemUser.username == username).first()


def query_system_user_with_page(data_param) -> Paging:
    filter_s = []

    if data_param.get('id_s'):
        filter_s.append(SystemUser.id.in_(data_param.get('id_s')))

    if data_param.get('username'):
        filter_s.append(SystemUser.username == data_param.get('username'))

    if data_param.get('real_name'):
        filter_s.append(SystemUser.real_name == data_param.get('real_name'))

    if data_param.get('status'):
        filter_s.append(SystemUser.status == data_param.get('status'))

    session = get_db_session()
    return session.query(SystemUser) \
        .filter(*filter_s) \
        .order_by(SystemUser.id.desc()) \
        .paginate(page=data_param.get('page'), per_page=data_param.get('page_size'), error_out=False)
